package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowDataVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 检测设备Service业务层处理
 *
 * @author laoYe
 * @date 2025-10-28
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient ioTDAClient;


    /**
     * 查询检测设备
     *
     * @param id 检测设备主键
     * @return 检测设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询检测设备列表
     *
     * @param device 检测设备
     * @return 检测设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增检测设备
     *
     * @param device 检测设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改检测设备
     *
     * @param device 检测设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除检测设备
     *
     * @param ids 需要删除的检测设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除检测设备信息
     *
     * @param id 检测设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() {
        //看华为云官方文档
        ListProductsRequest request = new ListProductsRequest();
        //看华为云官方文档,用iotclient是因为老师已经封装好一个方法了
        ListProductsResponse response = ioTDAClient.listProducts(request);
        //转成productVO再返回
        List<ProductSummary> products = response.getProducts();
        //如果有产品数据则存入redis

        if (CollUtil.isNotEmpty(products)) {
            redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
        }
    }

    @Override
    public List<ProductVo> getAllProduct() {
        //1从redis中查询
        String product = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //转成productVO再返回
        if (product != null) {
            return JSONUtil.toList(product, ProductVo.class);

        }
        return List.of();
    }

    /**
     * 新增设备
     *
     * @param dto
     */
    @Transactional
    @Override
    public void insert(DeviceDto dto) {
        //1设备名称是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (count > 0) {
            throw new RuntimeException("设备名称重复");
        }
        //设备标识是否重复
        count = lambdaQuery().eq(Device::getNodeId, dto.getNodeId()).count();
        if (count > 0) {
            throw new RuntimeException("设备标识重复");
        }
        //同一位置是否绑定相同的产品
        count = lambdaQuery().eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new RuntimeException("同一位置绑定相同产品");
        }
        //保存到数据库中'=
        //生成设备id,生成规则为produck_id + _ + node_id拼接而成。
        String iotID = dto.getProductKey() + "_" + dto.getNodeId();
        dto.setIotId(iotID);
        //生成密钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        //转成数据对象
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        //是否有门禁，默认为0
        device.setHaveEntranceGuard(0);
        //添加到数据库
        save(device);
        //在华为云平台注册设备
        addDevice(dto, secret);

    }

    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //先查数据库的信息
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        //再查平台上的 信息
        //先判断数据库返回的数据是否存在，不存在就没必要查
        if (device != null) {
            DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
            ShowDeviceRequest request = new ShowDeviceRequest();
            request.withDeviceId(iotId);

            try {
                ShowDeviceResponse response = ioTDAClient.showDevice(request);
                //设备的状态
                vo.setDeviceStatus(response.getStatus());
                //设备的激活时间
                //此时时间格式不对的， 需要转换一下
                String actTime = response.getActiveTime();
                LocalDateTime activeTime = LocalDateTimeUtil.parse(actTime, DatePattern.UTC_MS_PATTERN);
                activeTime = activeTime
                        //这各时间对象是当前所在的时区为0时区
                        .atZone(ZoneId.from(ZoneOffset.UTC))
                        //转换成上海时区 东8区 +8小时
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                vo.setActiveTime(activeTime);
                return vo;
            } catch (Exception e) {
                log.error("查询设备详细失败：{}", iotId);
                throw new RuntimeException(e);
            }
        }

        //两者进行组装返回
        return null;
    }

    /**
     * 3.5.8 查看设备上报的数据
     *
     * @param iotId
     * @return
     */

    @Override
    public List<DeviceShadowDataVo> queryDeviceDetailList(String iotId) {
        //查询iot平台上的设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        try {
            ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
            DeviceShadowProperties reportod = response.getShadow().get(0).getReported();
            String reportedTimeStr = reportod.getEventTime();
            LocalDateTime reportedTime = LocalDateTimeUtil.parse(reportedTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"))
                    // 这个时间对象当前所在的时区为0时区
                    .atZone(ZoneId.from(ZoneOffset.UTC))

                    // 转成上海时区 东8区 +8小时
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            // LinkedHashMap
            LinkedHashMap<String, Object> properties = (LinkedHashMap<String, Object>) reportod.getProperties();
            //遍历这个HashMap 转成vo返回
            List<DeviceShadowDataVo> voList = new ArrayList<>();
            properties.forEach((k, v) -> {
                DeviceShadowDataVo vo = new DeviceShadowDataVo();
                vo.setFunctionId(k);
                vo.setValue(String.valueOf(v));
                vo.setEventTime(reportedTime);
                voList.add(vo);

            });
            return voList;

        } catch (ServiceResponseException e) {
            e.printStackTrace();

        }
        return List.of();

    }

    /**
     * 向华为云平台新增设备
     *
     * @param dto
     */
    private void addDevice(DeviceDto dto, String secret) {
        AddDeviceRequest request = new AddDeviceRequest();
        // 设备本身的信息
        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        // 生成设备id 生成规则为product_id + _ + node_id拼接而成。
        body.withDeviceId(dto.getIotId());
        request.withBody(body);

        AuthInfo authInfo = new AuthInfo();
        //秘钥
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);

        request.withBody(body);
        try {
            AddDeviceResponse response = ioTDAClient.addDevice(request);
            System.out.println("response.getDeviceId() = " + response.getDeviceId());
        } catch (Exception e) {
            log.error("注册设备失败", e);
            throw new RuntimeException(e);
        }
    }
}
